﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ventas.Data.Entities;

namespace Ventas.Data.Managers
{
    public class ProductManager
    {
        //
        public static IList<Product> GetList(string filter)
        {
            using (VentasDbContext ctx = new VentasDbContext())
            {
                return ctx.Products.Where(u => u.Codigo.Contains(filter)).Include(t => t.Category).ToList();
            }
        }
        //
        public static Product Create(Product product)
        {
            using (VentasDbContext ctx = new VentasDbContext())
            {
                product.Category = ctx.Categorys.Find(product.CategoryId);
                Product productDB = ctx.Products.Add(product);

                ctx.SaveChanges();
                return productDB;
            }
        }
        //
        public static Product Update(Product product)
        {
            using (VentasDbContext ctx = new VentasDbContext())
            {
                product.Category = ctx.Categorys.Find(product.CategoryId);
                ctx.Entry(product).State = EntityState.Modified;

                ctx.SaveChanges();
                return product;
            }
        }
        //
        public static Product GetById(Guid id)
        {
            using (VentasDbContext ctx = new VentasDbContext())
            {
                Product productDB = ctx.Products.Find(id);
                if (productDB == null)
                {
                    throw new Exception("Product not found in data base");
                }
                return productDB;
            }
        }
        //
        public static void Delete(Guid id)
        {
            using (VentasDbContext ctx = new VentasDbContext())
            {
                Product ProductDB = ctx.Products.Find(id);
                if (ProductDB == null)
                {
                    throw new Exception("Product not found in data base");
                }
                ctx.Products.Remove(ProductDB);
                ctx.SaveChanges();
            }
        }
    }
        
}
